﻿using System;
using System.Web.UI;
using BLL;
using DAL;
using Ext.Net;
using System.Data;
using Roles;

namespace ERP.Modules
{
    public partial class OrderBuyMain : UserControl
    {
        #region[Define]
        private static bool _flag;
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                txtDateBegin.Text = DateTime.Now.ToString();
                txtDateBeginPay.Text = DateTime.Now.ToString();
                txtDateEndPay.Text = DateTime.Now.ToString();
                GetOrderBuy();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
            }
        }
        //Store
        protected void StoreOrderBuy_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            txtDateBeginFillter.Text = string.Empty;
            txtDateEndFillter.Text = string.Empty;
            GetOrderBuy();
        }
        protected void StoreOrderBuy_Detail_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            if (_flag)
            {
                if (String.IsNullOrEmpty(txtOrder_ID.Text))
                {
                    GetOrderBuyDetailTemp();
                    GetOrderBuyDetailTempSum();
                }
                else
                {
                    GetOrderEdit(int.Parse(txtOrder_ID.Text));
                    GetOrderWithOrder(int.Parse(txtOrder_ID.Text));
                }
            }
            else
            {
                GetOrderBuyEdit(int.Parse(txtOrderBuy_ID.Text));
                GetOrderBuySum(int.Parse(txtOrderBuy_ID.Text));
            }
        }
        protected void StoreOrderWithOrder_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            GetOrder();
        }
        protected void StoreMaterial_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            GetMaterials();
        }
        protected void StoreCustomerOrderBuy_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            GetCustomer();
        }
        //Button
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            _flag = true;
            txtOrderBuyCode.ReadOnly = true;
            btnRefreshOrderBuyCode.Enable(true);
            btnAddCustomer.Enable(true);
            btnAddMaterial.Enable(true);
            btnDelMaterial.Enable(true);
            btnAddOrderCode.Enable(true);
            btnDelOrderCode.Enable(true);
            ClearText();
            GetAutoID();
            WindowsOrderBuy.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grOrderBuy.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    _flag = false;
                    txtOrderBuyCode.ReadOnly = true;
                    btnRefreshOrderBuyCode.Disable(true);
                    GetOrderBuyEdit(int.Parse(row.RecordID));
                    GetOrderBuySum(int.Parse(row.RecordID));
                    WindowsOrderBuy.Show();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            try
            {
                var sm = grOrderBuy.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        var obj = new EtOrderBuy { Order_Buy_Id = int.Parse(row.RecordID) };
                        BllOrderBuy.Delete(obj);
                        if (obj.Msg == 0)
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan,không thể xoá !");
                        if (obj.Msg == 2)
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan,không thể xoá !");
                    }
                GetOrderBuy();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        protected void btnFillter_Click(object sender, DirectEventArgs e)
        {
            GetOrderBuyFillterDate();
        }
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnAddMaterial_Click(object sender, DirectEventArgs e)
        {
            var sm = grMaterial.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null) sm.DeselectAll();
            GetMaterials();
            WindowMaterial.Show();
        }
        protected void btnDelMaterial_Click(object sender, DirectEventArgs e)
        {
            if (_flag)
            {
                var sm = grOrderBuy_Detail.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        try
                        {
                            DeleteDetail(int.Parse(row.RecordID), 1);
                        }
                        catch (Exception)
                        {
                            HTML.clsFormat.Alert_ERROR("Thông Báo",
                                "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                        }
                    }
                GetOrderBuyDetailTemp();
            }
            else
            {
                var sm = grOrderBuy_Detail.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        try
                        {
                            DeleteDetail(int.Parse(row.RecordID), 0);
                        }
                        catch (Exception)
                        {
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                        }
                    }
                GetOrderBuyEdit(int.Parse(txtOrder_ID.Text));
            }
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            ClearText();
            WindowsOrderBuy.Close();
        }
        protected void btnRefreshOrderBuyCode_Click(object sender, DirectEventArgs e)
        {
            GetAutoID();
        }
        protected void btnAddCustomer_Click(object sender, DirectEventArgs e)
        {
            var sm = grCustomerOrderBuy.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null) sm.DeselectAll();
            GetCustomer();
            WindowCustomerOrderBuy.Show();
        }
        protected void btnSelectMaterial_Click(object sender, DirectEventArgs e)
        {
            if (_flag)
            {
                InsertDetail();
            }
            else
            {
                UdpateDetail();
            }
        }
        protected void btnAddOrderCode_Click(object sender, DirectEventArgs e)
        {
            var sm = grOrderWithOrder.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null) sm.DeselectAll();
            GetOrder();
            WindowOrderWithOrder.Show();
        }
        protected void btnDelOrderCode_Click(object sender, DirectEventArgs e)
        {
            txtOrder_ID.Text = string.Empty;
            txtOrder_Code.Text = string.Empty;
            txtCustomerID.Text = string.Empty;
            txtCustomerName.Text = string.Empty;
            txtCustomerAlias.Text = string.Empty;
            txtCustomerAddress.Text = string.Empty;
            lbQualityWithOrderBuy.Text = string.Empty;
            lbPriceWithOrderBuy.Text = string.Empty;
            lbPriCKWithOrderBuy_Total.Text = string.Empty;
            lbPriVATWithOrderBuy.Text = string.Empty;
            lbTotalCostOrderBuyWithOrderBuy.Text = string.Empty;

            btnAddCustomer.Enable(true);
            btnAddMaterial.Enable(true);
            btnDelMaterial.Enable(true);
            grOrderBuy_Detail.GetStore().RemoveAll();
        }
        //Double-Click
        protected void OrderBuyDblClick(object sender, DirectEventArgs e)
        {
            _flag = false;
            int Order_Buy_Id = int.Parse(e.ExtraParams["Order_Buy_Id"]);
            txtOrderBuyCode.ReadOnly = true;
            btnRefreshOrderBuyCode.Disable(true);
            GetOrderBuyEdit(Order_Buy_Id);
            GetOrderBuySum(Order_Buy_Id);
            WindowsOrderBuy.Show();
        }
        //Cell-Click
        protected void CellOrderBuyCustomer_Click(object sender, DirectEventArgs e)
        {
            var sm = grCustomerOrderBuy.GetSelectionModel() as CellSelectionModel;
            if (sm != null)
            {
                string id = sm.SelectedCell.RecordID;
                GetCustomerEdit(int.Parse(id));
                sm.Clear();
                sm.UpdateSelection();
            }
            WindowCustomerOrderBuy.Close();
        }
        protected void CellOrderWithOrder_Click(object sender, DirectEventArgs e)
        {
            var sm = grOrderWithOrder.GetSelectionModel() as CellSelectionModel;
            if (sm != null)
            {
                string id = sm.SelectedCell.RecordID;
                DeleteAdd(int.Parse(Session["Users_Id"].ToString()), 1);
                GetOrderEdit(int.Parse(id));
                GetOrderWithOrder(int.Parse(id));
                sm.Clear();
                sm.UpdateSelection();
            }
            WindowOrderWithOrder.Close();
            btnAddCustomer.Disable(true);
            btnAddMaterial.Disable(true);
            btnDelMaterial.Disable(true);
        }
        //Cell-Update
        protected void UpdateMaterials_Click(object sender, DirectEventArgs e)
        {
            if (String.IsNullOrEmpty(txtOrder_ID.Text))
            {
                var GetOrder_Detail = e.ExtraParams["grOrderBuy_Detail"];
                var dtgrOrder_Detail = JSON.Deserialize<DataTable>(GetOrder_Detail);
                foreach (DataRow rows in dtgrOrder_Detail.Rows)
                {
                    UpdateQuanlity(int.Parse(rows["Order_Buy_Detail_Id"].ToString()),
                        int.Parse(rows["Order_Detail_Quality"].ToString()),
                        float.Parse(rows["Order_Detail_Price"].ToString()),
                        float.Parse(rows["Order_Detail_CK_Percent"].ToString()),
                        float.Parse(rows["Order_Detail_VAT_Percent"].ToString()),
                        int.Parse(rows["Order_Buy_Id"].ToString()));
                }
            }
            else
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", "Số lượng đã được phê duyệt.Bạn không được thay đổi !");
            }
        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            var _clsGetOrder = new BllOrder();
            var _dtSearch = _clsGetOrder.GetOrder(txtSearch.Text);
            if (_dtSearch != null && _dtSearch.Rows.Count > 0)
            {
                StoreOrderBuy.DataSource = _dtSearch;
                StoreOrderBuy.DataBind();
            }
            else
            {
                grOrderBuy.GetStore().RemoveAll();
            }
        }
        #endregion

        #region[Method]
        private void GetOrder()
        {
            var _clsOrder = new BllOrderBuy();
            var _dtOrder = _clsOrder.GetOrder_IsUsed(string.Empty, 0, 1);
            if (_dtOrder != null && _dtOrder.Rows.Count > 0)
            {
                StoreOrderWithOrder.DataSource = _dtOrder;
                StoreOrderWithOrder.DataBind();
            }
            else
            {
                grOrderWithOrder.GetStore().RemoveAll();
            }
        }
        private void GetOrderEdit(int id)
        {
            var _clsGetOrderEdit = new BllOrder();
            var _dtGetOrder = _clsGetOrderEdit.GetOrderDetailEdit(id, 0);
            if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
            {
                txtOrder_ID.Text = _dtGetOrder.Rows[0]["Order_Id"].ToString();
                txtOrder_Code.Text = _dtGetOrder.Rows[0]["Order_Code"].ToString();
                txtCustomerAlias.Text = _dtGetOrder.Rows[0]["Customer_Alias"].ToString();
                txtCustomerName.Text = _dtGetOrder.Rows[0]["Customer_Name"].ToString();
                txtCustomerID.Text = _dtGetOrder.Rows[0]["Customer_ID"].ToString();
                txtCustomerAddress.Text = _dtGetOrder.Rows[0]["Customer_Address"].ToString();
                txtTaxCode.Text = _dtGetOrder.Rows[0]["Customer_Contract_Tax_Code"].ToString();
                StoreOrderBuy_Detail.DataSource = _dtGetOrder;
                StoreOrderBuy_Detail.DataBind();
            }
            else
            {
                grOrderBuy_Detail.GetStore().RemoveAll();
            }
        }
        private void GetOrderBuy()
        {
            var _clsGetOrderBuy = new BllOrderBuy();
            var _dtGetOrderBuy = _clsGetOrderBuy.GetOrderBuy(txtSearch.Text);
            if (_dtGetOrderBuy != null && _dtGetOrderBuy.Rows.Count > 0)
            {
                StoreOrderBuy.DataSource = _dtGetOrderBuy;
                StoreOrderBuy.DataBind();
            }
            else
            {
                grOrderBuy.GetStore().RemoveAll();
            }
        }
        private void GetOrderBuyEdit(int id)
        {
            try
            {
                var _clsGetOrderBuyEdit = new BllOrderBuy();
                #region[Get-Data]
                var _dtGetOrderBuy = _clsGetOrderBuyEdit.GetOrderBuyDetailEdit(id, 0);
                if (_dtGetOrderBuy != null && _dtGetOrderBuy.Rows.Count > 0)
                {
                    txtOrderBuy_ID.Text = _dtGetOrderBuy.Rows[0]["Order_Buy_Id"].ToString();
                    txtOrder_ID.Text = _dtGetOrderBuy.Rows[0]["Order_Id"].ToString();
                    txtOrderBuyCode.Text = _dtGetOrderBuy.Rows[0]["Order_Buy_Code"].ToString();
                    txtOrder_Code.Text = _dtGetOrderBuy.Rows[0]["Order_Code"].ToString();
                    txtDateBegin.Text = _dtGetOrderBuy.Rows[0]["Order_Buy_DateBegin"].ToString();
                    txtDateEndPay.Text = _dtGetOrderBuy.Rows[0]["Order_Buy_DateEnd"].ToString();
                    txtTaxCode.Text = _dtGetOrderBuy.Rows[0]["Order_Buy_Tax_Code"].ToString();
                    txtDescription.Text = _dtGetOrderBuy.Rows[0]["Order_Buy_Description"].ToString();
                    txtCustomerAlias.Text = _dtGetOrderBuy.Rows[0]["Customer_Alias"].ToString();
                    txtCustomerName.Text = _dtGetOrderBuy.Rows[0]["Customer_Name"].ToString();
                    txtCustomerID.Text = _dtGetOrderBuy.Rows[0]["Customer_ID"].ToString();
                    txtCustomerAddress.Text = _dtGetOrderBuy.Rows[0]["Customer_Address"].ToString();
                    txtTaxCode.Text = _dtGetOrderBuy.Rows[0]["Customer_Contract_Tax_Code"].ToString();
                    #region[Check]
                    var obj = new EtOrderBuyDetail { Order_Buy_Id = id };
                    BllOrderBuy.GetOrderCheck(obj);
                    if (obj.Msg == 0)
                    {
                        btnAddMaterial.Disable(true);
                        btnDelMaterial.Disable(true);
                        btnAddOrderCode.Disable(true);
                        btnDelOrderCode.Disable(true);
                        btnAddCustomer.Disable(true);
                    }
                    else if (obj.Msg == 1)
                    {
                        btnAddMaterial.Disable(true);
                        btnDelMaterial.Disable(true);
                        btnAddOrderCode.Disable(true);
                        btnDelOrderCode.Disable(true);
                        btnAddCustomer.Disable(true);
                    }
                    else if (String.IsNullOrEmpty(_dtGetOrderBuy.Rows[0]["Order_Id"].ToString())
                         || _dtGetOrderBuy.Rows[0]["Order_Id"].ToString() == DBNull.Value.ToString()
                         || _dtGetOrderBuy.Rows[0]["Order_Id"].ToString() == "-1")
                    {
                        btnAddMaterial.Enable(true);
                        btnDelMaterial.Enable(true);
                        btnAddOrderCode.Enable(true);
                        btnDelOrderCode.Enable(true);
                        btnAddCustomer.Enable(true);
                    }
                    else
                    {
                        btnAddMaterial.Disable(true);
                        btnDelMaterial.Disable(true);
                        btnAddOrderCode.Disable(true);
                        btnDelOrderCode.Disable(true);
                        btnAddCustomer.Disable(true);
                    }
                    #endregion
                    StoreOrderBuy_Detail.DataSource = _dtGetOrderBuy;
                    StoreOrderBuy_Detail.DataBind();
                }
                else
                {
                    grOrderBuy_Detail.GetStore().RemoveAll();
                }
                #endregion
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void GetOrderBuySum(int id)
        {
            var _clsGetOrderBuyEdit = new BllOrderBuy();
            var _dtGetOrderBuy = _clsGetOrderBuyEdit.GetOrderBuyDetailSum(id, 0);
            if (_dtGetOrderBuy != null && _dtGetOrderBuy.Rows.Count > 0)
            {
                lbQualityWithOrderBuy.Text = _dtGetOrderBuy.Rows[0]["TotalMaterial"].ToString();
                lbPriceWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrderBuy.Rows[0]["TotalPrice"]).Replace(".", ",");
                lbPriCKWithOrderBuy_Total.Text = String.Format("{0:0,00}", _dtGetOrderBuy.Rows[0]["TotalCK"]).Replace(".", ",");
                lbPriVATWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrderBuy.Rows[0]["TotalVAT"]).Replace(".", ",");
                lbTotalCostOrderBuyWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrderBuy.Rows[0]["TotalALL"]).Replace(".", ",");
            }
        }
        private void GetOrderWithOrder(int id)
        {
            var _clsGetOrderEdit = new BllOrder();
            var _dtGetOrder = _clsGetOrderEdit.GetOrderDetailSum(id, 0);
            if (_dtGetOrder != null && _dtGetOrder.Rows.Count > 0)
            {
                lbQualityWithOrderBuy.Text = _dtGetOrder.Rows[0]["TotalMaterial"].ToString();
                lbPriceWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalPrice"]).Replace(".", ",");
                lbPriCKWithOrderBuy_Total.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalCK"]).Replace(".", ",");
                lbPriVATWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalVAT"]).Replace(".", ",");
                lbTotalCostOrderBuyWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrder.Rows[0]["TotalALL"]).Replace(".", ",");
            }
        }
        private void GetOrderBuyDetailTemp()
        {
            var _clsGetOrderBuyEdit = new BllOrderBuy();
            var _dtGetOrderBuy = _clsGetOrderBuyEdit.GetOrderBuyDetailEditTmep(1, int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetOrderBuy != null && _dtGetOrderBuy.Rows.Count > 0)
            {
                StoreOrderBuy_Detail.DataSource = _dtGetOrderBuy;
                StoreOrderBuy_Detail.DataBind();
            }
            else
            {
                grOrderBuy_Detail.GetStore().RemoveAll();
            }
        }
        private void GetOrderBuyDetailTempSum()
        {
            var _clsGetOrderBuyEdit = new BllOrderBuy();
            var _dtGetOrderBuy = _clsGetOrderBuyEdit.GetOrderBuyDetailEditTmepSum(1, int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetOrderBuy != null && _dtGetOrderBuy.Rows.Count > 0)
            {
                lbQualityWithOrderBuy.Text = _dtGetOrderBuy.Rows[0]["TotalMaterial"].ToString();
                lbPriceWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrderBuy.Rows[0]["TotalPrice"]).Replace(".", ",");
                lbPriCKWithOrderBuy_Total.Text = String.Format("{0:0,00}", _dtGetOrderBuy.Rows[0]["TotalCK"]).Replace(".", ",");
                lbPriVATWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrderBuy.Rows[0]["TotalVAT"]).Replace(".", ",");
                lbTotalCostOrderBuyWithOrderBuy.Text = String.Format("{0:0,00}", _dtGetOrderBuy.Rows[0]["TotalALL"]).Replace(".", ",");
            }
        }
        private void GetMaterials()
        {
            var _clsMaterials = new Materials_BLL();
            var _dtMaterials = _clsMaterials.GetMaterials();
            if (_dtMaterials != null && _dtMaterials.Rows.Count > 0)
            {
                StoreMaterial.DataSource = _dtMaterials;
                StoreMaterial.DataBind();
            }
            else
            {
                grMaterial.GetStore().RemoveAll();
            }
        }
        private void GetCustomer()
        {
            var _clsCustomer = new Customer_BLL();
            var _dtCustomer = _clsCustomer.BindGirdtb_Customer(string.Empty);
            if (_dtCustomer != null && _dtCustomer.Rows.Count > 0)
            {
                StoreCustomerOrderBuy.DataSource = _dtCustomer;
                StoreCustomerOrderBuy.DataBind();
            }
            else
            {
                grCustomerOrderBuy.GetStore().RemoveAll();
            }
        }
        private void GetCustomerEdit(int id)
        {
            var _clsCustomer = new Customer_BLL();
            var _dtCustomerEdit = _clsCustomer.GetCustomerDetail(id);
            if (_dtCustomerEdit != null && _dtCustomerEdit.Rows.Count > 0)
            {
                txtCustomerID.Text = _dtCustomerEdit.Rows[0]["Customer_ID"].ToString();
                txtCustomerAlias.Text = _dtCustomerEdit.Rows[0]["Customer_Alias"].ToString();
                txtCustomerName.Text = _dtCustomerEdit.Rows[0]["Customer_Name"].ToString();
                txtCustomerAddress.Text = _dtCustomerEdit.Rows[0]["Customer_Address"].ToString();
                txtTaxCode.Text = _dtCustomerEdit.Rows[0]["Customer_Contract_Tax_Code"].ToString();
            }
        }
        private void GetOrderBuyFillterDate()
        {
            if (String.IsNullOrEmpty(txtDateBeginFillter.Text) && String.IsNullOrEmpty(txtDateEndFillter.Text))
            {
                var _clsGetOrderBuy = new BllOrderBuy();
                var _dtGetOrderBuy = _clsGetOrderBuy.GetOrderBuy(txtSearch.Text);
                if (_dtGetOrderBuy != null && _dtGetOrderBuy.Rows.Count > 0)
                {
                    StoreOrderBuy.DataSource = _dtGetOrderBuy;
                    StoreOrderBuy.DataBind();
                }
                else
                {
                    grOrderBuy.GetStore().RemoveAll();
                }
            }
            else
            {
                var _clsGetOrderBuy = new BllOrderBuy();
                var _dtGetOrderBuy = _clsGetOrderBuy.GetOrderBuyFillterDate(txtDateBeginFillter.Text, txtDateEndFillter.Text);
                if (_dtGetOrderBuy != null && _dtGetOrderBuy.Rows.Count > 0)
                {
                    StoreOrderBuy.DataSource = _dtGetOrderBuy;
                    StoreOrderBuy.DataBind();
                }
                else
                {
                    grOrderBuy.GetStore().RemoveAll();
                }
            }
        }
        private void GetAutoID()
        {
            var _clsBllCreateCode = new BllCreateCode();
            var _dtGetAutoID = _clsBllCreateCode.GetAutoID("Order_Buy_Code", "tb_Order_Buy");
            if (_dtGetAutoID != null && _dtGetAutoID.Rows.Count > 0)
            {
                try
                {
                    txtOrderBuyCode.Text = "DMH-" + DateTime.Now.ToString("yyMM") + "-000" +
                                            Convert.ToString(int.Parse(_dtGetAutoID.Rows[0]["Auto_ID"].ToString()) +
                                                             int.Parse(1.ToString()));
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                }
            }
        }
        private bool CheckInsert()
        {
            bool check = false;
            var _clsCheck = new BllOrderBuy();
            var _dtCheck = _clsCheck.GetOrderBuy(txtSearch.Text);
            if (_dtCheck != null && _dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtCheck.Rows)
                {
                    if (txtOrderBuyCode.Text == dr["Order_Buy_Code"].ToString())
                    {
                        check = true;
                    }
                }
            }
            return check;
        }
        private bool CheckInsertDetail(int Materials_Id)
        {
            bool check = false;
            var _clsCheck = new BllOrderBuy();
            var _dtCheck = _clsCheck.GetOrderBuyDetailEditTmep(1, int.Parse(Session["Users_Id"].ToString()));
            if (_dtCheck != null && _dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtCheck.Rows)
                {
                    if (Materials_Id == int.Parse(dr["Materials_Id"].ToString()))
                    {
                        check = true;
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (_flag)
            {
                InsertValue();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Bạn không được cấp phép thay đổi dữ liệu !");
                }
                else
                {
                    UpdateValue();
                }
            }
        }
        private void InsertValue()
        {
            try
            {
                if (CheckInsert())
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Chứng từ này đã tồn tại !");
                }
                else
                {
                    var _clsGetOrderBuyEdit = new BllOrderBuy();
                    var _dtGetOrderBuy = _clsGetOrderBuyEdit.GetOrderBuyDetailEditTmep(1,
                        int.Parse(Session["Users_Id"].ToString()));
                    if (_dtGetOrderBuy.Rows.Count < 0)
                    {
                        HTML.clsFormat.Alert_ERROR("Lỗi", "Vui lòng chọn vật tư để thêm mới !");
                    }
                    else
                    {
                        var obj = new EtOrderBuy
                        {
                            Order_Buy_Code = txtOrderBuyCode.Text,
                            Order_Id = String.IsNullOrEmpty(txtOrder_ID.Text) ? (int?)null : int.Parse(txtOrder_ID.Text),
                            Order_Buy_Tax_Code = txtTaxCode.Text,
                            Order_Buy_DateBegin = DateTime.Parse(txtDateBegin.Text),
                            Customer_ID = int.Parse(txtCustomerID.Text),
                            Order_Buy_DateEnd = DateTime.Parse(txtDateEndPay.Text),
                            Order_Buy_Payment_Type = string.Empty,
                            Users_Id = int.Parse(Session["Users_Id"].ToString()),
                            Order_Buy_Description = txtDescription.Text,
                            Order_Buy_Uesr_ID = int.Parse(Session["Users_Id"].ToString())
                        };
                        if (String.IsNullOrEmpty(txtOrder_ID.Text))
                        {
                            BllOrderBuy.Insert(obj);
                        }
                        else
                        {
                            InsertDetailOrder();
                            BllOrderBuy.Insert(obj);
                        }
                        HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                        GetOrderBuy();
                        ClearText();
                    }
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateValue()
        {
            var obj = new EtOrderBuy
            {
                Order_Buy_Id = int.Parse(txtOrderBuy_ID.Text),
                Order_Buy_Tax_Code = txtTaxCode.Text,
                Order_Buy_Description = txtDescription.Text
            };
            BllOrderBuy.Update(obj);
            HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật thành công !");
            GetOrderBuy();
        }
        private void InsertDetailOrder()
        {
            try
            {
                var obj = new EtOrderBuyDetail
                {
                    Order_Id = int.Parse(txtOrder_ID.Text),
                    Users_Id = int.Parse(Session["Users_Id"].ToString()),
                    Flag = 1
                };
                BllOrderBuy.InsertDetailOrder(obj);
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void InsertDetail()
        {
            try
            {
                var sm = grMaterial.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        if (CheckInsertDetail(int.Parse(row.RecordID)))
                        {
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Vật tư này đã tồn tại !");
                        }
                        else
                        {
                            var obj = new EtOrderBuyDetail
                            {
                                Order_Buy_Id = null,
                                Materials_Id = int.Parse(row.RecordID),
                                Order_Detail_Quality = 0,
                                Order_Detail_Price = 0,
                                Order_Detail_CK_Percent = 0,
                                Order_Detail_CK = 0,
                                Order_Detail_VAT_Percent = 0,
                                Order_Detail_VAT = 0,
                                Order_Detail_Total_Price = 0,
                                IsActive = false,
                                Users_Id = int.Parse(Session["Users_Id"].ToString()),
                                Flag = 1
                            };
                            BllOrderBuy.InsertDetail(obj);
                            HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới vật tư thành công");
                        }
                    }
                GetOrderBuyDetailTemp();
                GetOrderBuyDetailTempSum();
                WindowMaterial.Close();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UdpateDetail()
        {
            try
            {
                var sm = grMaterial.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    foreach (var row in sm.SelectedRows)
                    {
                        if (CheckInsertDetail(int.Parse(row.RecordID)))
                        {
                            HTML.clsFormat.Alert_ERROR("Lỗi", "Vật tư này đã tồn tại !");
                        }
                        else
                        {
                            var obj = new EtOrderBuyDetail
                            {
                                Order_Buy_Id = int.Parse(txtOrderBuy_ID.Text),
                                Materials_Id = int.Parse(row.RecordID),
                                Order_Detail_Quality = 0,
                                Order_Detail_Price = 0,
                                Order_Detail_CK_Percent = 0,
                                Order_Detail_CK = 0,
                                Order_Detail_VAT_Percent = 0,
                                Order_Detail_VAT = 0,
                                Order_Detail_Total_Price = 0,
                                IsActive = false,
                                Users_Id = int.Parse(Session["Users_Id"].ToString()),
                                Flag = 0
                            };
                            BllOrderBuy.InsertDetail(obj);
                            HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới vật tư thành công");
                        }
                    }
                GetOrderBuyEdit(int.Parse(txtOrderBuy_ID.Text));
                GetOrderBuySum(int.Parse(txtOrderBuy_ID.Text));
                WindowMaterial.Close();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateQuanlity(int OrderBuy_Detail_Id, int OrderBuy_Detail_Quality, float OrderBuy_Detail_Price, float OrderBuy_Detail_CK_Percent,
            float OrderBuy_Detail_VAT_Percent, int Order_Buy_Id)
        {
            try
            {
                var obj = new EtOrderBuyDetail
                {
                    Order_Buy_Id = Order_Buy_Id,
                    Order_Detail_Id = OrderBuy_Detail_Id,
                    Order_Detail_Quality = OrderBuy_Detail_Quality,
                    Order_Detail_Price = OrderBuy_Detail_Price,
                    Order_Detail_CK_Percent = OrderBuy_Detail_CK_Percent,
                    Order_Detail_VAT_Percent = OrderBuy_Detail_VAT_Percent
                };
                BllOrderBuy.UpdateQuanlity(obj);
                if (obj.Msg == 0)
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan không thể thay đổi mẫu tin !");
                }
                else if (obj.Msg == 2)
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi", "Có chứng từ liên quan không thể thay đổi mẫu tin !");
                }
                else
                {
                    if (_flag)
                    {
                        GetOrderBuyDetailTemp();
                        GetOrderBuyDetailTempSum();
                    }
                    else
                    {
                        GetOrderBuyEdit(int.Parse(txtOrderBuy_ID.Text));
                        GetOrderBuySum(int.Parse(txtOrderBuy_ID.Text));
                    }
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật thành công !");
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void DeleteDetail(int OrderBuy_Detail_Id, int Flag)
        {
            try
            {
                var obj = new EtOrderBuyDetail { Order_Detail_Id = OrderBuy_Detail_Id, Flag = Flag };
                BllOrderBuy.DeleteDetail(obj);
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void DeleteAdd(int Users_Id, int Flag)
        {
            try
            {
                var obj = new EtOrderBuyDetail { Users_Id = Users_Id, Flag = Flag };
                BllOrderBuy.DeleteAdd(obj);
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        #endregion

        #region[ClearText]
        private void ClearText()
        {
            FormPanelOrderBuy.Reset();
            DeleteAdd(int.Parse(Session["Users_Id"].ToString()), 1);
            grOrderBuy_Detail.GetStore().RemoveAll();
            lbQualityWithOrderBuy.Text = string.Empty;
            lbPriceWithOrderBuy.Text = string.Empty;
            lbPriCKWithOrderBuy_Total.Text = string.Empty;
            lbPriVATWithOrderBuy.Text = string.Empty;
            lbTotalCostOrderBuyWithOrderBuy.Text = string.Empty;
            txtOrder_ID.Text = string.Empty;
            txtOrderBuy_ID.Text = string.Empty;
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.OrderBuyMain, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelOrderBuyMain.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            bool check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.OrderBuyMain, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion

        #region[Print]
        protected void MenuItemExportExcel_Click(object sender, DirectEventArgs e)
        {
            try
            {
                var _clsGetServerUpload = new BLLsaddicServerUpload();
                var _dtGetServerUpload = _clsGetServerUpload.GetServerUpload();
                var sm = grOrderBuy.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                    if (sm.SelectedRows.Count > 1)
                    {
                        HTML.clsFormat.Alert_ERROR("Lỗi", "Bạn chỉ được phép chọn một dòng để in dữ liệu !");
                    }
                    else
                    {
                        foreach (var row in sm.SelectedRows)
                        {
                            var _clsGetReport = new BllReportSell();
                            var _dtGetReport = _clsGetReport.GetReportBuy(int.Parse(row.RecordID));
                            if (_dtGetReport != null && _dtGetReport.Rows.Count > 0)
                            {
                                if (_dtGetServerUpload != null && _dtGetServerUpload.Rows.Count > 0)
                                {
                                    LibGlobal.Export.ExcelExport(_dtGetReport,
                                        Server.MapPath(_dtGetServerUpload.Rows[2]["Path_Download"].ToString()),
                                        Server.MapPath(_dtGetServerUpload.Rows[2]["Path_Upload"].ToString()));
                                    LibGlobal.Export.DownloadFile(
                                        _dtGetServerUpload.Rows[2]["Path_Download"].ToString(),
                                        _dtGetServerUpload.Rows[2]["Page_Name"].ToString(),
                                    _dtGetServerUpload.Rows[2]["Extend"].ToString());
                                }
                            }
                        }
                        HTML.clsFormat.Alert_INFO("Thông Báo", "In thành công !");
                    }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        #endregion
    }
}